import "dart:convert";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/detail/lock_detail_notifier.dart";
import "package:ct_pa_majordomo/pages/device/lock/lock_wifi/index.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:flutter/foundation.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:provider/provider.dart";
import "package:ttlock_flutter/ttlock.dart";

import "sections/lock_info.dart";
import "sections/operation.dart";

class Detail extends StatefulWidget {
  final Map lockInfo;
  const Detail({super.key, required this.lockInfo,});

  @override
  State<Detail> createState() => _DetailState();
}

class _DetailState extends State<Detail> {
  final LockDetailNotifier _controller = LockDetailNotifier();
  Map? _info;

  void _getLockDetail () async {
    _controller.setNeedRefresh(false);
    EasyLoading.show();
    try {
      Map resData = await lockApi.getLockInfo(widget.lockInfo["lockId"]);
      setState(() {
        _info = resData["data"];
        print("lockdata: >>> ${_info?["lockData"]}");
        _controller.setInfo(_info!);
        Map lockInfo = jsonDecode(_info?["lockInfo"] ?? "{}");
        Provider.of<CommonState>(context, listen: false).setLock(_info!);
        Provider.of<CommonState>(context, listen: false).setLockInfo(lockInfo);
      });
      EasyLoading.dismiss();
    } catch(e) {
      EasyLoading.dismiss();
    }
  }

  List<Widget> kDebugModeWidget() {
    if (!kDebugMode) return [];
    return [
      SizedBox(height: 12,),
      Button(
        type: ButtonType.primary,
        child: Text("重置门锁"),
        onPressed: () {
          EasyLoading.show();
          TTLock.getBluetoothState((state) {
            print("回调：$state");
            if (state == TTBluetoothState.turnOn) {
              TTLock.resetLock(_info?["lockData"], () {
                EasyLoading.showToast("门锁重置成功");
              }, (errorCode, errorMsg) {
                EasyLoading.dismiss();
              });
            }
          });
        },
      ),
      SizedBox(height: 12,),
      Button(
        type: ButtonType.primary,
        child: Text("获取锁远程开关状态"),
        onPressed: () {
          EasyLoading.show();
          TTLock.getBluetoothState((state) {
            print("回调：$state");
            if (state == TTBluetoothState.turnOn) {
              TTLock.getLockRemoteUnlockSwitchState(_info?["lockData"], (opened) {
                EasyLoading.showToast(opened ? "开启" : "关闭");
              }, (errorCode, errorMsg) {
                EasyLoading.dismiss();
              });
            }
          });
        },
      ),
      SizedBox(height: 12,),
      Button(
        type: ButtonType.primary,
        child: Text("开启远程开关锁"),
        onPressed: () {
          EasyLoading.show();
          TTLock.getBluetoothState((state) {
            print("回调：$state");
            if (state == TTBluetoothState.turnOn) {
              TTLock.setLockRemoteUnlockSwitchState(true, _info?["lockData"], (msg) {
                EasyLoading.showSuccess(msg);
                print(msg);
              }, (errorCode, errorMsg) {
                EasyLoading.showError("$errorCode: $errorMsg");
                print("$errorCode: $errorMsg");
              });
            }
          });
        },
      ),
      SizedBox(height: 12,),
      Button(
        type: ButtonType.primary,
        child: Text("设置常开模式"),
        onPressed: () {
          EasyLoading.show();
          TTLock.getBluetoothState((state) {
            print("回调：$state");
            if (state == TTBluetoothState.turnOn) {
              int startTime = 0 * 60; //8:00 am
              int endTime = 24 * 60; //23:00 pm
              List<int> weekly = [1, 2, 3, 4, 5, 6, 7]; // [Monday，Tuesday]
              TTLock.clearAllPassageModes(_info?["lockData"], (){
                EasyLoading.showSuccess("关闭常开模式");
              }, (code, msg){});
              // TTLock.addPassageMode(TTPassageModeType.weekly, weekly, null, startTime,
              //     endTime, _info?["lockData"], () {
              //       EasyLoading.showSuccess("Success");
              //     }, (errorCode, errorMsg) {
              //       EasyLoading.showError("$errorCode, $errorMsg");
              //     });
            }
            EasyLoading.dismiss();
          });
        },
      ),
      SizedBox(height: 12,),
      Button(
        type: ButtonType.primary,
        child: Text("清除常开模式"),
        onPressed: () {
          EasyLoading.show();
          TTLock.getBluetoothState((state) {
            print("回调：$state");
            if (state == TTBluetoothState.turnOn) {
              TTLock.clearAllPassageModes(_info?["lockData"], (){
                EasyLoading.showSuccess("关闭常开模式");
              }, (errorCode, errorMsg) {
                EasyLoading.showError("$errorCode, $errorMsg");
              });
            }
            EasyLoading.dismiss();
          });
        },
      ),
      SizedBox(height: 12,),
      Button(
        type: ButtonType.primary,
        child: Text("设置wifi"),
        onPressed: () {
          print("数据:>>>>>>>>>>>>>>>>>>${_info?["lockData"]}");
          Stacker.pushNamed(Keys.DEVICE_LOCK_WIFI, arguments: {"lockId": int.parse(_info?["lockId"]), "lockData": _info?["lockData"], "type": ConfigType.sett});
        },
      ),
      SizedBox(height: 12,),
      Button(
        type: ButtonType.primary,
        child: Text("关闭省电模式"),
        onPressed: () {
          EasyLoading.show(status: "正在关闭");
          TTLock.setLockConfig(TTLockConfig.wifiLockPowerSavingMode, false, _info?["lockData"], () async {
            await lockApi.lockSetting(int.parse(_info?["lockId"]), {
              "lockId": int.parse(_info?["lockId"]),
              "changeType": 1,
              "type": 10,
              "value": 2,
            });
            EasyLoading.showSuccess("关闭成功");
          }, (errorCode, errorMsg) {
            EasyLoading.showError("$errorCode: $errorMsg");
          },);
        },
      ),
      SizedBox(height: 12,),
      Button(
        type: ButtonType.primary,
        child: Text("获取省电模式状态"),
        onPressed: () {
          EasyLoading.show(status: "正在获取");
          TTLock.getLockConfig(TTLockConfig.wifiLockPowerSavingMode, _info?["lockData"], (state) {
            EasyLoading.showSuccess("当前状态是$state：${state ? "开启" : "关闭"}");
          }, (errorCode, errorMsg) {
            EasyLoading.showError("$errorCode: $errorMsg");
          },);
        },
      ),
      SizedBox(height: 12,),
      Button(
        type: ButtonType.primary,
        child: Text("获取wifi信息"),
        onPressed: () async {
          EasyLoading.show();
          TTLock.getBluetoothState((state) {
            print("回调：$state");
            if (state == TTBluetoothState.turnOn) {
              TTLock.getWifiInfo(_info?["lockData"], (value) {
                print("wifiInfo:>>>>>> $value");
                EasyLoading.showSuccess("获取成功");
              }, (errorCode, errorMsg) {
                EasyLoading.showError("$errorCode: $errorMsg");
              },);
            }});
          // Map resData = await lockApi.getWifiLockInfo(int.parse(_info?["lockId"]));
          // print("wifi信息：》》》》》》》》$resData");
          // EasyLoading.showSuccess("获取成功");
        },
      ),
      SizedBox(height: 12,),
      Button(
        type: ButtonType.primary,
        child: Text("更新"),
        onPressed: () {
          EasyLoading.show(status: "正在更新中...");
          TTLock.configServer("wifilock.ttlock.com", "4999", _info?["lockData"], () {
            TTLock.getWifiInfo(_info?["lockData"], (wifiInfo) async {
              Map<String, dynamic> data = {
                "lockId": _info?["lockId"],
                "wifiName": "一只猪",
                "wifiPassword": "1qazxsw2.",
              };
              await lockApi.updateNetwork(data);
              EasyLoading.showSuccess("更新成功");
            }, (errorCode, errorMsg) {
              EasyLoading.showError("$errorCode: $errorMsg");
            },);
          }, (errorCode, errorMsg) {
            EasyLoading.showError("$errorCode: $errorMsg");
          },);
        },
      ),
    ];
  }

  @override
  void initState() {
    _getLockDetail();
    _controller.addListener(() {
      if (_controller.needRefresh) {
        _getLockDetail();
      }
    });
    super.initState();
  }


  @override
  void dispose() {
    print("停止监听");
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    if (_controller.needRefresh) {
      _getLockDetail();
    }

    return Scaffold(
      appBar: AppBar(
        iconTheme: const IconThemeData(color: Colors.white),
        title: const Text("智能锁", style: TextStyle(color: Colors.white),),
        centerTitle: true,
        backgroundColor: ThemeVars.colorPrimary,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 20),
        children: [
          LockInfo(controller: _controller, onchange: (update) {
            if (update) {
              _getLockDetail();
            }
          },),
          const SizedBox(height: 15,),
          Operation(controller: _controller,),
          SizedBox(height: 30,),
          Button(
            type: ButtonType.primary,
            child: Text("网关开锁"),
            onPressed: () async {
              EasyLoading.show();
              await lockApi.unLock(int.parse(widget.lockInfo["lockId"]));
              EasyLoading.showToast("开锁成功");
            },
          ),
          SizedBox(height: 12,),
          Button(
            type: ButtonType.primary,
            child: Text("蓝牙开锁"),
            onPressed: () {
              EasyLoading.show();
              TTLock.getBluetoothState((state) {
                print("回调：$state");
                if (state == TTBluetoothState.turnOn) {
                  TTLock.controlLock(_info?["lockData"], TTControlAction.unlock,
                          (lockTime, electricQuantity, uniqueId) {
                        EasyLoading.showSuccess("开锁成功");
                      }, (errorCode, errorMsg) {
                        EasyLoading.showError("$errorCode, $errorMsg");
                      });
                } else {
                  EasyLoading.dismiss();
                }
              });
            },
          ),
          ...kDebugModeWidget(),
        ],
      ),
    );
  }

}